import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Card,
  Upload,
  Button,
  Steps,
  Form,
  Input,
  Select,
  InputNumber,
  message,
  Progress,
  Space,
  Divider,
  Row,
  Col,
  Typography,
  Result,
  List,
  Tag,
  Collapse,
  Alert,
  Spin,
} from "antd";
import {
  UploadOutlined,
  FileTextOutlined,
  EditOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  DownloadOutlined,
  RobotOutlined,
  BookOutlined,
  FilePptOutlined,
} from "@ant-design/icons";
import type { UploadProps } from "antd";
import styled from "styled-components";
import { API_ENDPOINTS } from "../../../config/env";
import { httpPost, aiHttpPost, aiHttpStream } from "../../../utils/http";
import { aiAPI } from "../../../services/api";
import PPTPreview from "./PPTPreview";
import ErrorBoundary from "./ErrorBoundary";

// 类型定义
interface FileContent {
  content: string;
  filename: string;
}

interface KnowledgePoint {
  name: string;
  content: string;
  subtopics: string[];
}

interface PPTOutline {
  title: string;
  slides: Array<{
    title: string;
    content: string[];
    image_prompt: string;
    detail: string;
  }>;
}

interface GeneratedContent {
  knowledgePoints: KnowledgePoint[];
  exercises: Exercise[];
  timeDistribution: TimeDistribution;
  pptOutline?: PPTOutline;
}

interface Exercise {
  title: string;
  difficulty: "easy" | "medium" | "hard";
  type: "choice" | "programming" | "analysis";
}

interface TimeDistribution {
  theory: number;
  practice: number;
  qa: number;
}

interface FormValues extends Omit<GeneratedContent, "exercises"> {
  exercises: (Exercise & { key: string })[];
}

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { Panel } = Collapse;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const ContentPreview = styled.div`
  padding: 24px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-top: 16px;
`;

const TeacherPreparation: React.FC = () => {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(0);
  const [generatingContent, setGeneratingContent] = useState(false);
  const [generatedContent, setGeneratedContent] = useState<GeneratedContent | null>(null);
  const [form] = Form.useForm();
  const [autoSaveTimer, setAutoSaveTimer] = useState<NodeJS.Timeout | null>(null);
  const [lastSaved, setLastSaved] = useState<Date | null>(null);
  const [pptPreviewVisible, setPptPreviewVisible] = useState(false);
  const [aiGenerating, setAiGenerating] = useState(false);
  const [aiSuggestions, setAiSuggestions] = useState<string[]>([]);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [fileContent, setFileContent] = useState<string>("");
  const [knowledgePoints, setKnowledgePoints] = useState<KnowledgePoint[]>([]);
  const [pptOutline, setPptOutline] = useState<PPTOutline | null>(null);
  const [generatingPPT, setGeneratingPPT] = useState(false);
  const [courseTitle, setCourseTitle] = useState<string>("");
  const [courseDetails, setCourseDetails] = useState<string>("");

  // 文件上传配置
  const uploadProps: UploadProps = {
    name: "file",
    accept: ".doc,.docx,.pdf,.txt",
    beforeUpload: (file) => {
      setUploadedFile(file);
      return false; // 阻止自动上传
    },
    onChange(info) {
      if (info.file.status === "removed") {
        setUploadedFile(null);
        setFileContent("");
      }
    },
  };

  // 步骤1：上传文件并分析内容
  const handleFileUpload = async () => {
    if (!uploadedFile) {
      message.error("请先选择文件");
      return;
    }

    if (!courseTitle.trim()) {
      message.error("请输入课程标题");
      return;
    }

    setGeneratingContent(true);
    try {
      // 1. 上传文件到Python后端进行分析
      const response = await aiAPI.generateOutline(uploadedFile);
      
      if (!response.ok) {
        throw new Error("文件分析失败");
      }

      // 2. 获取文件内容
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法读取响应");
      }

      let content = "";
      const decoder = new TextDecoder();
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            if (data && data !== '[DONE]') {
              try {
                const parsed = JSON.parse(data);
                if (parsed.data) {
                  content += parsed.data;
                }
              } catch (e) {
                // 忽略解析错误
              }
            }
          }
        }
      }

      setFileContent(content);
      
      // 3. 调用AI分析提炼内容
      await analyzeFileContent(content);
      
      message.success("文件分析完成！");
      setCurrentStep(1);
    } catch (error) {
      console.error("文件分析失败:", error);
      message.error("文件分析失败，请重试");
    } finally {
      setGeneratingContent(false);
    }
  };

  // 分析文件内容
  const analyzeFileContent = async (content: string) => {
    setAiGenerating(true);
    let aiResponseData = "";

    try {
      // 构建更详细的分析提示词
      const analysisPrompt = `
请对以下课程内容进行深度分析，生成结构化的教学建议：

课程标题：${courseTitle}
${courseDetails ? `课程细节：${courseDetails}` : ''}

课程内容：
${content}

请严格按照以下JSON格式返回分析结果，包含：
1. 知识点分析：从内容中提取的核心知识点
2. 教学建议：基于内容的AI教学建议
3. 练习题建议：适合的练习题类型和内容
4. 时间分配：合理的教学时间分配

要求：
- 所有分析必须严格基于提供的课程内容
- 知识点要准确反映内容的核心要点
- 教学建议要具体可操作
- 练习题要与知识点对应
- 时间分配要合理

请直接返回JSON格式，不要包含其他文字。
      `;

      await aiHttpStream(API_ENDPOINTS.AI.CHAT, {
        message: analysisPrompt
      }, 
      (message) => {
        aiResponseData += message;
      },
      (error) => {
        console.error("AI分析失败:", error);
        message.error("AI分析失败，请重试");
      },
      () => {
        // 完成后的处理
        if (aiResponseData) {
          try {
            // 尝试解析JSON格式的分析结果
            const analysisMatch = aiResponseData.match(/\{[\s\S]*\}/);
            if (analysisMatch) {
              const analysis = JSON.parse(analysisMatch[0]);
              
              // 使用AI分析结果生成结构化内容
              const structuredContent: GeneratedContent = {
                knowledgePoints: analysis.knowledgePoints || [
                  {
                    name: "基础概念",
                    content: "从课程内容中提取的基础理论知识",
                    subtopics: ["概念定义", "基本原理", "核心要素"]
                  },
                  {
                    name: "实践应用",
                    content: "从课程内容中提取的实际应用技能",
                    subtopics: ["操作步骤", "注意事项", "常见问题"]
                  }
                ],
                exercises: analysis.exercises || [
                  {
                    title: "基础概念理解练习",
                    difficulty: "easy",
                    type: "choice"
                  },
                  {
                    title: "实践操作练习",
                    difficulty: "medium",
                    type: "programming"
                  }
                ],
                timeDistribution: analysis.timeDistribution || {
                  theory: 45,
                  practice: 60,
                  qa: 15
                }
              };

              setGeneratedContent(structuredContent);
              setKnowledgePoints(structuredContent.knowledgePoints);
              setAiSuggestions(analysis.suggestions || []);
              
              // 生成PPT大纲
              generatePPTOutline(content);
            } else {
              // 如果无法解析JSON，使用默认内容
              const defaultContent: GeneratedContent = {
                knowledgePoints: [
                  {
                    name: "基础概念",
                    content: "从课程内容中提取的基础理论知识",
                    subtopics: ["概念定义", "基本原理", "核心要素"]
                  },
                  {
                    name: "实践应用",
                    content: "从课程内容中提取的实际应用技能",
                    subtopics: ["操作步骤", "注意事项", "常见问题"]
                  }
                ],
                exercises: [
                  {
                    title: "基础概念理解练习",
                    difficulty: "easy",
                    type: "choice"
                  },
                  {
                    title: "实践操作练习",
                    difficulty: "medium",
                    type: "programming"
                  }
                ],
                timeDistribution: {
                  theory: 45,
                  practice: 60,
                  qa: 15
                }
              };

              setGeneratedContent(defaultContent);
              setKnowledgePoints(defaultContent.knowledgePoints);
              
              // 解析AI建议
              const suggestions = aiResponseData
                .split("\n")
                .filter((line: string) => line.trim().length > 0);
              setAiSuggestions(suggestions);
              
              // 生成PPT大纲
              generatePPTOutline(content);
            }
          } catch (parseError) {
            console.warn("AI分析结果解析失败，使用默认内容");
            // 使用默认内容
            const defaultContent: GeneratedContent = {
              knowledgePoints: [
                {
                  name: "基础概念",
                  content: "从课程内容中提取的基础理论知识",
                  subtopics: ["概念定义", "基本原理", "核心要素"]
                },
                {
                  name: "实践应用",
                  content: "从课程内容中提取的实际应用技能",
                  subtopics: ["操作步骤", "注意事项", "常见问题"]
                }
              ],
              exercises: [
                {
                  title: "基础概念理解练习",
                  difficulty: "easy",
                  type: "choice"
                },
                {
                  title: "实践操作练习",
                  difficulty: "medium",
                  type: "programming"
                }
              ],
              timeDistribution: {
                theory: 45,
                practice: 60,
                qa: 15
              }
            };

            setGeneratedContent(defaultContent);
            setKnowledgePoints(defaultContent.knowledgePoints);
            
            // 解析AI建议
            const suggestions = aiResponseData
              .split("\n")
              .filter((line: string) => line.trim().length > 0);
            setAiSuggestions(suggestions);
            
            // 生成PPT大纲
            generatePPTOutline(content);
          }
        }
      });
    } catch (error) {
      console.error("AI分析失败:", error);
      message.error("AI分析失败，请重试");
    } finally {
      setAiGenerating(false);
    }
  };

  // 生成PPT大纲
  const generatePPTOutline = async (content: string) => {
    try {
      let pptOutlineData = "";
      
      // 构建完整的课程信息用于PPT生成
      const pptCourseInfo = `
课程标题：${courseTitle}
${courseDetails ? `细节补充：${courseDetails}` : ''}

课程内容：${content}
      `;

      await aiHttpStream(API_ENDPOINTS.AI.CHAT, {
        message: `基于以下课程内容，生成一个专业的PPT大纲，确保布局和条理完全符合PPT的美感：

${pptCourseInfo}

PPT设计要求：
1. 结构清晰：包含封面、目录、内容页、总结页
2. 内容美观：每页内容要简洁明了，层次分明
3. 布局合理：标题、要点、说明的布局要符合PPT设计规范
4. 视觉层次：使用不同的字体大小、颜色、间距来体现层次
5. 逻辑连贯：页面之间的逻辑关系要清晰
6. 教学友好：适合教学使用，便于学生理解

具体格式要求：
- 每页幻灯片包含：标题、内容要点（3-5个）、详细说明
- 内容要点要简洁，使用项目符号
- 详细说明要补充要点内容，但不要过长
- 整体风格要专业、美观、易读

请以JSON格式返回，包含title和slides数组，每个slide包含title、content数组、detail字段。
确保生成的PPT大纲具有专业的美感和清晰的结构。`
      }, 
      (message) => {
        pptOutlineData += message;
      },
      (error) => {
        console.error("PPT大纲生成失败:", error);
      },
      () => {
        // 完成后的处理
        try {
          // 尝试解析JSON格式的PPT大纲
          const outlineMatch = pptOutlineData.match(/\{[\s\S]*\}/);
          if (outlineMatch) {
            const outline = JSON.parse(outlineMatch[0]);
            setPptOutline(outline);
            setGeneratedContent(prev => prev ? { ...prev, pptOutline: outline } : null);
          }
        } catch (parseError) {
          console.warn("PPT大纲解析失败，使用默认大纲");
          // 使用默认PPT大纲，确保美观和结构清晰
          const defaultOutline: PPTOutline = {
            title: courseTitle || "专业教学课件",
            slides: [
              {
                title: "课程概述",
                content: [
                  "📚 课程名称：" + (courseTitle || "数据结构"),
                  "👨‍🏫 授课教师：XXX",
                  "📅 课程时间：2025年春季学期",
                  "🎯 学习目标：掌握核心概念并应用于实际场景"
                ],
                image_prompt: "",
                detail: "本页介绍课程的基本信息、目标和适用对象，为后续学习奠定基础。"
              },
              {
                title: "核心知识点",
                content: [
                  "🔍 重点概念：基础理论知识的核心要点",
                  "⚡ 关键原理：支撑理论的重要原理",
                  "🛠️ 重要方法：实用的操作方法和技巧",
                  "📊 知识结构：各知识点之间的关联关系"
                ],
                image_prompt: "",
                detail: "详细讲解课程的核心知识点，帮助学生建立扎实的理论基础。"
              },
              {
                title: "实践应用",
                content: [
                  "💻 操作步骤：具体的实践操作流程",
                  "⚠️ 注意事项：实践过程中的关键要点",
                  "📋 案例分析：典型应用场景的详细分析",
                  "🎯 应用技巧：提高实践效率的方法"
                ],
                image_prompt: "",
                detail: "展示实际应用和操作过程，让学生能够将理论知识转化为实践技能。"
              },
              {
                title: "学习总结",
                content: [
                  "📝 知识回顾：本课程的核心要点总结",
                  "🔗 知识联系：与其他课程的关联关系",
                  "🚀 拓展方向：进一步学习的方向和建议",
                  "💡 学习建议：提高学习效果的方法"
                ],
                image_prompt: "",
                detail: "总结课程内容，帮助学生巩固所学知识，并为后续学习提供指导。"
              }
            ]
          };
          setPptOutline(defaultOutline);
          setGeneratedContent(prev => prev ? { ...prev, pptOutline: defaultOutline } : null);
        }
      });
    } catch (error) {
      console.error("PPT大纲生成失败:", error);
    }
  };

  // 打开PPT预览
  const handleGeneratePPT = () => {
    console.log("handleGeneratePPT called");
    console.log("uploadedFile:", uploadedFile);
    console.log("fileContent:", fileContent);
    console.log("generatedContent:", generatedContent);
    console.log("knowledgePoints:", knowledgePoints);
    console.log("aiSuggestions:", aiSuggestions);
    console.log("pptOutline:", pptOutline);
    console.log("currentStep:", currentStep);

    // 检查是否在正确的步骤
    if (currentStep !== 1) {
      message.error("请先完成内容分析步骤");
      return;
    }

    // 检查必要的数据
    if (!generatedContent) {
      message.error("请先完成内容分析");
      return;
    }

    // 检查是否有基本内容
    if (!knowledgePoints || knowledgePoints.length === 0) {
      message.error("请先完成知识点分析");
      return;
    }

    setPptPreviewVisible(true);
  };

  const handleAutoSave = async (values: any) => {
    try {
      console.log("Auto saving...", values);
      setLastSaved(new Date());
      message.success("自动保存成功", 1);
    } catch (error) {
      console.error("Auto save failed:", error);
      message.error("自动保存失败，请手动保存");
    }
  };

  const handleFormChange = () => {
    if (autoSaveTimer) {
      clearTimeout(autoSaveTimer);
    }

    const timer = setTimeout(async () => {
      const values = await form.validateFields().catch(() => null);
      if (values) {
        handleAutoSave(values);
      }
    }, 30000);

    setAutoSaveTimer(timer);
  };

  useEffect(() => {
    return () => {
      if (autoSaveTimer) {
        clearTimeout(autoSaveTimer);
      }
    };
  }, [autoSaveTimer]);

  const handleSave = async (values: FormValues) => {
    try {
      console.log("保存的内容：", values);
      setLastSaved(new Date());
      message.success("保存成功！");
      setCurrentStep(2);
    } catch (error) {
      console.error("Save failed:", error);
      message.error("保存失败，请重试");
    }
  };

  const steps = [
    {
      title: "内容生成",
      description: "上传课程大纲并生成教学内容",
    },
    {
      title: "内容调整",
      description: "调整生成的教学内容",
    },
    {
      title: "完成",
      description: "预览并保存",
    },
  ];

  return (
    <div>
      <Steps current={currentStep} items={steps} style={{ marginBottom: 24 }} />

      {currentStep === 0 && (
        <StyledCard title="上传课程大纲">
          <Space direction="vertical" style={{ width: "100%" }}>
            <Alert
              message="智能备课助手"
              description="上传课程大纲文件，AI将自动分析内容，提炼知识点，并生成教学PPT"
              type="info"
              showIcon
              icon={<RobotOutlined />}
              style={{ marginBottom: 16 }}
            />
            
            {/* 课程标题输入 */}
            <div>
              <Text strong style={{ display: 'block', marginBottom: 8 }}>
                课程标题 <Text type="danger">*</Text>
              </Text>
              <Input
                placeholder="请输入课程标题"
                value={courseTitle}
                onChange={(e) => setCourseTitle(e.target.value)}
                style={{ marginBottom: 16 }}
              />
            </div>

            {/* 细节补充输入 */}
            <div>
              <Text strong style={{ display: 'block', marginBottom: 8 }}>
                细节补充
              </Text>
              <TextArea
                placeholder="请输入课程细节补充信息（可选）"
                value={courseDetails}
                onChange={(e) => setCourseDetails(e.target.value)}
                rows={4}
                style={{ marginBottom: 16 }}
              />
            </div>
            
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            
            <Paragraph type="secondary">
              支持上传 Word、PDF、TXT 格式的课程大纲文件
            </Paragraph>

            {uploadedFile && (
              <Alert
                message={`已选择文件：${uploadedFile.name}`}
                type="success"
                showIcon
                action={
                  <Button size="small" onClick={() => setUploadedFile(null)}>
                    重新选择
                  </Button>
                }
              />
            )}

            <Button
              type="primary"
              icon={<FileTextOutlined />}
              onClick={handleFileUpload}
              loading={generatingContent || aiGenerating}
              disabled={!uploadedFile || !courseTitle.trim()}
              style={{ marginTop: 16 }}
            >
              {aiGenerating ? "AI 正在分析内容..." : "开始分析内容"}
            </Button>

            {(generatingContent || aiGenerating) && (
              <Progress
                percent={aiGenerating ? 75 : 45}
                status="active"
                style={{ marginTop: 16 }}
              />
            )}

            {aiSuggestions.length > 0 && (
              <Card title="AI 分析建议" size="small" style={{ marginTop: 16 }}>
                <List
                  size="small"
                  dataSource={aiSuggestions}
                  renderItem={(item, index) => (
                    <List.Item>
                      <Text>{index + 1}. {item}</Text>
                    </List.Item>
                  )}
                />
              </Card>
            )}
          </Space>
        </StyledCard>
      )}

      {currentStep === 1 && generatedContent && (
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          onChange={handleFormChange}
          initialValues={generatedContent}
        >
          <StyledCard title="📚 知识点梳理" style={{ marginBottom: 24 }}>
            <Alert
              message="基于上传文件内容分析的知识点"
              description="AI已从您的课程文件中提取出核心知识点，您可以根据需要进行调整"
              type="info"
              showIcon
              style={{ marginBottom: 16 }}
            />
            <List
              dataSource={knowledgePoints}
              renderItem={(item, index) => (
                <List.Item>
                  <Card 
                    size="small" 
                    style={{ width: "100%", border: "1px solid #e8f4fd", borderRadius: 8 }}
                    title={
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ fontSize: 16, fontWeight: 'bold', color: '#1890ff' }}>
                          {index + 1}. {item.name}
                        </span>
                      </div>
                    }
                  >
                    <Paragraph style={{ color: '#666', marginBottom: 12 }}>
                      {item.content}
                    </Paragraph>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                      {item.subtopics.map((subtopic, subIndex) => (
                        <Tag 
                          key={subIndex} 
                          color="blue" 
                          style={{ 
                            borderRadius: 16, 
                            padding: '4px 12px',
                            fontSize: 12,
                            border: '1px solid #91d5ff',
                            backgroundColor: '#f0f8ff'
                          }}
                        >
                          {subtopic}
                        </Tag>
                      ))}
                    </div>
                  </Card>
                </List.Item>
              )}
            />
          </StyledCard>



          <StyledCard title="练习题">
            <Form.List name="exercises">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Card key={key} size="small" style={{ marginBottom: 16 }}>
                      <Row gutter={16}>
                        <Col span={8}>
                          <Form.Item
                            {...restField}
                            name={[name, "title"]}
                            rules={[{ required: true, message: "请输入题目" }]}
                          >
                            <Input placeholder="题目" />
                          </Form.Item>
                        </Col>
                        <Col span={4}>
                          <Form.Item
                            {...restField}
                            name={[name, "difficulty"]}
                            rules={[{ required: true, message: "请选择难度" }]}
                          >
                            <Select placeholder="难度">
                              <Option value="easy">简单</Option>
                              <Option value="medium">中等</Option>
                              <Option value="hard">困难</Option>
                            </Select>
                          </Form.Item>
                        </Col>
                        <Col span={4}>
                          <Form.Item
                            {...restField}
                            name={[name, "type"]}
                            rules={[{ required: true, message: "请选择类型" }]}
                          >
                            <Select placeholder="类型">
                              <Option value="choice">选择题</Option>
                              <Option value="programming">编程题</Option>
                              <Option value="analysis">分析题</Option>
                            </Select>
                          </Form.Item>
                        </Col>
                        <Col span={4}>
                          <Button
                            type="link"
                            danger
                            onClick={() => remove(name)}
                          >
                            删除
                          </Button>
                        </Col>
                      </Row>
                    </Card>
                  ))}
                  <Button type="dashed" onClick={() => add()} block>
                    添加练习题
                  </Button>
                </>
              )}
            </Form.List>
          </StyledCard>

          <StyledCard title="时间分配">
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item
                  label="理论讲解"
                  name={["timeDistribution", "theory"]}
                  initialValue={generatedContent.timeDistribution.theory}
                >
                  <InputNumber<number>
                    min={0}
                    max={120}
                    formatter={(value) => `${value}分钟`}
                    parser={(value) => {
                      const parsed = value
                        ? parseInt(value.replace("分钟", ""))
                        : 0;
                      return Math.min(Math.max(parsed, 0), 120);
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="实践操作"
                  name={["timeDistribution", "practice"]}
                  initialValue={generatedContent.timeDistribution.practice}
                >
                  <InputNumber<number>
                    min={0}
                    max={120}
                    formatter={(value) => `${value}分钟`}
                    parser={(value) => {
                      const parsed = value
                        ? parseInt(value.replace("分钟", ""))
                        : 0;
                      return Math.min(Math.max(parsed, 0), 120);
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="答疑互动"
                  name={["timeDistribution", "qa"]}
                  initialValue={generatedContent.timeDistribution.qa}
                >
                  <InputNumber<number>
                    min={0}
                    max={120}
                    formatter={(value) => `${value}分钟`}
                    parser={(value) => {
                      const parsed = value
                        ? parseInt(value.replace("分钟", ""))
                        : 0;
                      return Math.min(Math.max(parsed, 0), 120);
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </StyledCard>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存备课内容
              </Button>
              <Button 
                type="primary" 
                icon={<FilePptOutlined />}
                onClick={handleGeneratePPT}
                loading={generatingPPT}
              >
                生成PPT
              </Button>
              <Button onClick={() => setCurrentStep(0)}>返回</Button>
              {lastSaved && (
                <Text type="secondary">
                  上次保存: {lastSaved.toLocaleTimeString()}
                </Text>
              )}
            </Space>
          </Form.Item>
        </Form>
      )}

      {currentStep === 2 && (
        <StyledCard title="备课完成">
          <Result
            status="success"
            title="备课内容已保存"
            subTitle="您可以在课件资源管理中查看和编辑此教案"
            extra={[
              <Button
                type="primary"
                key="continue"
                onClick={() => setCurrentStep(0)}
              >
                继续备课
              </Button>,
              <Button key="resources" onClick={() => navigate("/teacher/resources")}>
                查看所有教案
              </Button>,
            ]}
          />
        </StyledCard>
      )}

      {/* PPT预览模态框 */}
      <ErrorBoundary>
        <PPTPreview
          visible={pptPreviewVisible}
          onClose={() => setPptPreviewVisible(false)}
          courseData={{
            title: courseTitle || uploadedFile?.name || "课程",
            content: fileContent || "课程内容",
            knowledgePoints: knowledgePoints || [],
            aiSuggestions: aiSuggestions || [],
            pptOutline: pptOutline || null,
          }}
        />
      </ErrorBoundary>
    </div>
  );
};

export default TeacherPreparation;
